package com.hdoit.apollo.web.wechat.controllers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.apollo.logical.cargo.model.Cargo;
import com.hdoit.apollo.logical.cargo.service.ICargoService;
import com.hdoit.apollo.logical.shop.model.Customer;
import com.hdoit.apollo.logical.shop.model.Shop;
import com.hdoit.apollo.logical.shop.service.ICustomerService;
import com.hdoit.apollo.logical.shop.service.IShopService;
import com.hdoit.apollo.logical.viewmodel.wechat.FavoriteSearch;
import com.hdoit.apollo.logical.wechat.model.Favorite;
import com.hdoit.apollo.logical.wechat.service.IFavoriteService;
import com.tennetcn.authority.component.web.JsonActionResult;
import com.tennetcn.core.common.enums.pub.YesOrNoInteger;
import com.tennetcn.core.common.message.ManageContainer;
import com.tennetcn.core.common.utils.CommonUtils;
import com.tennetcn.core.common.utils.DateUtils;
import com.tennetcn.data.enums.ModelStatus;
import com.tennetcn.data.message.PagerModel;
import com.tennetcn.web.message.WebManageContainer;
import com.tennetcn.webpage.web.base.BaseWebpage;
import com.tennetcn.webpage.web.component.annotation.WebpageAuthMode;
import com.tennetcn.webpage.web.enums.WebpageAuthEnum;
import com.tennetcn.webpage.web.message.WechatLoginModel;

/**
 * @author      humaoshu
 * @email       
 * @createtime  2018年09月03日 14:50:44
 * @comment
 */
@Controller
@RequestMapping(value = "/wechat/favorite/")
@WebpageAuthMode(validMode =WebpageAuthEnum.tryWechatAuth)
public class FavoriteController extends BaseWebpage{
    @Override
    public String getRoutePath() {
        return "areas/wechat/favorite/";
    }

    @Autowired
    private IFavoriteService favoriteService;
    
    @Autowired
    private ICargoService cargoService;
    
    @Autowired
    private ICustomerService customerService;
    
    @Autowired
    private IShopService shopService;

    private final String favoriteListViewName="favoriteList";
    private final String outputViewName="output";
    private final String detailedViewName="favoriteDetailed";
    private final String saveViewName="save";
    private final String deleteViewName = "delete";

    @RequestMapping(value = favoriteListViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String favoriteList(Model model,PagerModel pagerModel,String customerId,String shopId,String searchKey, FavoriteSearch search,boolean ajaxPost){

    	if (!StringUtils.isEmpty(customerId)) {
			search.setCustomerId(customerId);
		}
    	if (!StringUtils.isEmpty(searchKey)) {
			search.setSearchKey(searchKey);
		}
    	Shop shop=shopService.queryModel(shopId);
    	
    	if (webpageSession.getCurrentLogin()!=null) {
    		WechatLoginModel wechatLoginModel=webpageSession.getCurrentLogin().getWechatLoginModel();
    		System.err.println(wechatLoginModel.getHeadImgUrl()+"头像图片地址");
			String openId=wechatLoginModel.getOpenId();
			System.err.println(openId+"微信");
			Customer customer=customerService.queryModelByOpenId(openId,shopId);
			
			if (StringUtils.isEmpty(customer)&&!StringUtils.isEmpty(openId)) {
				Customer customered=new Customer();
				customered.setCustomerId(CommonUtils.getKeyId());
				customered.setCustomerName(wechatLoginModel.getNickName());
				customered.setNickName(wechatLoginModel.getNickName());
				customered.setOpenId(openId);
				customered.setCreateDate(DateUtils.getCurrent());
				customered.setDeleteMark(YesOrNoInteger.no);
				customered.setModelStatus(ModelStatus.add);
				customered.setShopId(shopId);
				
				customerService.applyChange(customered);
				customer=customerService.queryModelByOpenId(openId,shopId);
			}
			model.addAttribute("customer", customer);
		}
    	
    	 model.addAttribute("shop", shop);
    	
        pagerModel.setTotalAmount(favoriteService.queryCountMP(search));
        List<Favorite> favorites= favoriteService.queryListMP(search,pagerModel);

        model.addAttribute(WebManageContainer.PAGERKEY, pagerModel);
        model.addAttribute("favorites", favorites);
        model.addAttribute("favoriteSearch", search);

        if(ajaxPost){
            return view(outputViewName);
        }

        return view(favoriteListViewName);
    }

    @RequestMapping(value = detailedViewName, method = { RequestMethod.GET})
    public String favoriteDetailed(Model model,String key){
        Favorite favorite=new Favorite();
        if(!StringUtils.isEmpty(key)){
            favorite=favoriteService.queryModel(key);
        }
        model.addAttribute("favorite", favorite);
        return view(detailedViewName);
    }


    @RequestMapping(value = saveViewName, method = { RequestMethod.POST }, produces = "text/html;charset=UTF-8")
    public @ResponseBody String save(Model model,Favorite favorite,String cargoId){
    	
    	Cargo cargo=new Cargo();
    	if (!StringUtils.isEmpty(cargoId)) {
    		cargo=cargoService.queryCargoById(cargoId);
		}
    	if (webpageSession.getCurrentLogin()!=null) {
    		WechatLoginModel wechatLoginModel=webpageSession.getCurrentLogin().getWechatLoginModel();
			String openId=wechatLoginModel.getOpenId();
			
			Customer customer=customerService.queryModelByOpenId(openId,cargo.getShopId());
			if (StringUtils.isEmpty(customer)&&!StringUtils.isEmpty(openId)) {
				Customer customered=new Customer();
				customered.setCustomerId(CommonUtils.getKeyId());
				customered.setCustomerName(wechatLoginModel.getNickName());
				customered.setNickName(wechatLoginModel.getNickName());
				customered.setOpenId(openId);
				customered.setCreateDate(DateUtils.getCurrent());
				customered.setDeleteMark(YesOrNoInteger.no);
				customered.setModelStatus(ModelStatus.add);
				customered.setShopId(cargo.getShopId());
				
				customerService.applyChange(customered);
				customer=customerService.queryModelByOpenId(openId,cargo.getShopId());
			}
			
			Favorite favorited=favoriteService.queryModelByCargoIdAndCustomerId(cargoId,customer.getCustomerId());
			
			if (!StringUtils.isEmpty(favorited)) {
				favorite=favorited;
				favorite.setModifyDate(DateUtils.getCurrent());

	             favorite.setModelStatus(ModelStatus.update);
			}else {
				 favorite.setId(CommonUtils.getKeyId());
	             favorite.setCargoId(cargoId);
	             favorite.setShopId(cargo.getShopId());
	             favorite.setCustomerId(customer.getCustomerId());
	             favorite.setCreateDate(DateUtils.getCurrent());
	             favorite.setDeleteMark(YesOrNoInteger.no);
	             favorite.setModelStatus(ModelStatus.add);
			}
		}

        if(favoriteService.applyChange(favorite)){
        	return new JsonActionResult(ManageContainer.SUCCESS).toJson();
        }else{
        	return new JsonActionResult(ManageContainer.ERROR).toJson();
        }

    }

    @RequestMapping(value =deleteViewName, method = { RequestMethod.POST },produces="text/plain;charset=utf-8")
    public @ResponseBody String delete(String key){
        if(favoriteService.deleteFakeByKey(key)){
            return new JsonActionResult(ManageContainer.SUCCESS).toJson();
        }
        return new JsonActionResult(ManageContainer.ERROR).toJson();
    }
}